package com.cxx.purchasecharge.component.controller.usersecurity;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.PCApplicationContext;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.bean.usersecurity.AuthorityBean;
import com.cxx.purchasecharge.component.bean.usersecurity.ResourceBean;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.BeanConvertUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.Authority;
import com.cxx.purchasecharge.dal.AuthorityDao;

@Controller
@RequestMapping ("/authority")
public class AuthorityManager
{
    private static final Logger logger = Logger.getLogger (AuthorityManager.class);

    @Autowired
    private AuthorityDao authorityDao;
    @Autowired
    private PCApplicationContext pcContext;

    @RequestMapping (value = "/getAllAuthority", method = RequestMethod.POST)
    public @ResponseBody
    String getAuthoritys (DataGridRequestForm dataGridRequestForm)
    {
        List <Authority> authoritys = (List <Authority>) authorityDao.findAll ();

        JSONArray jsonArray = JSONArray.fromObject (BeanConvertUtils.authorityList2AuthorityBeanList (authoritys));
        return jsonArray.toString ();
    }

    @RequestMapping (value = "/newAuthority", method = RequestMethod.POST)
    public @ResponseBody
    String addAuthority (AuthorityBean authorityBean, BindingResult bindingResult, HttpServletRequest request)
    {
        preprocessAuthority (authorityBean, request);
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                authorityDao.save (BeanConvertUtils.authorityBean2Authority (authorityBean));
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/updateAuthority", method = RequestMethod.POST)
    public @ResponseBody
    String updateAuthority (AuthorityBean authorityBean, BindingResult bindingResult, HttpServletRequest request)
    {
        preprocessAuthority (authorityBean, request);
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                authorityDao.save (BeanConvertUtils.authorityBean2Authority (authorityBean));
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_FAIL,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    private void preprocessAuthority (AuthorityBean authBean, HttpServletRequest request)
    {
        String resources = request.getParameter ("resources");
        if (StringUtils.isNotBlank (resources))
        {
            List <ResourceBean> resourceBeans = new ArrayList <ResourceBean> ();
            ResourceBean resourceBean = null;
            String[] resourceArr = resources.split (",");
            for (String resourceId : resourceArr)
            {
                resourceBean = new ResourceBean ();
                resourceBean.setId (resourceId);
                resourceBeans.add (resourceBean);
            }
            authBean.setResourceBeans (resourceBeans);
        }
    }

    @RequestMapping (value = "/delAuthority", method = RequestMethod.POST)
    public @ResponseBody
    String deleteAuthority (@RequestParam String ids)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            Authority authority;
            List <Authority> authoritys = new ArrayList <Authority> ();
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String id : idArr)
                {
                    authority = new Authority ();
                    authority.setId (Long.parseLong (id));
                    authoritys.add (authority);
                }
            }
            else
            {
                authority = new Authority ();
                authority.setId (Long.parseLong (ids));
                authoritys.add (authority);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                authorityDao.delete (authoritys);
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                       ComponentConstants.MSG_AUTHORITY))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST);
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/")
    public String redirectToAuthorityManagement (ModelMap model)
    {
        return "authorityManagement";
    }

    @RequestMapping (value = "/checkExist", method = RequestMethod.POST)
    public @ResponseBody
    String checkExist (@RequestParam String authorityId, @RequestParam String name)
    {
        if (StringUtils.isBlank (authorityId))
        {
            // new
            Authority obj = authorityDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long uid = Long.parseLong (authorityId);
            Authority authority = authorityDao.findByName (name);
            if (null != authority && authority.getId () != uid)
            {
                return "false";
            }
        }

        return "true";
    }

}
